package com.nulldev.util.uri.yt.webVTT;

import java.util.LinkedList;
import java.util.regex.Pattern;

import com.nulldev.util.other.ArrayUtils;
import com.nulldev.util.string.StringsUtil;

public class SubtitleParser {

	public static class Subtitle {
		private final String text;
		private final double start, dur, end;
		
		public Subtitle(final String text, final double start, final double dur) {
			this.text = text;
			this.start = start;
			this.dur = dur;
			this.end = start + dur;
		}
		
		public String text() {
			return this.text;
		}
		
		public double start() {
			return this.start;
		}
		
		public double end() {
			return this.end;
		}
		
		public double duration() {
			return this.dur;
		}
		
		@Override
		public String toString() {
			return "Subtitle[start=" + this.start + ",duration=" + this.dur + ",end=" + this.end + ",text=" + this.text + "]";
		}
	}
	
	public static LinkedList<Subtitle> getSubtitles(final String data) {
		//<?xml version="1.0" encoding="utf-8" ?><transcript>
		final LinkedList<Subtitle> out = new LinkedList<Subtitle>();
		final String innerData = StringsUtil.substringBetweenO(data, 
				"<?xml version=\"1.0\" encoding=\"utf-8\" ?><transcript>", "</transcript>");
		final String[] entries = innerData.split(Pattern.quote("</text>"));
		for (final String entry : entries) {
			final String text = ArrayUtils.StringArrayUtils.addFrom(entry.split("\">"), 1);
			final double start = Double.parseDouble(StringsUtil.substringBetweenO(entry, "start=\"", "\""));
			final double dur = Double.parseDouble(StringsUtil.substringBetweenO(entry, "dur=\"", "\""));
			out.add(new Subtitle(text, start, dur));
		}
		return out;
	}
}
